<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>商品详情 - 网上跳蚤市场</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" th:href="@{/css/style.css}" />
    <link rel="stylesheet" th:href="@{/css/product-detail.css}" />
</head>
<body>
<div th:replace="layout :: .nav"></div>
<div class="container">
    <section class="card main-content">
        <h2>商品详情</h2>
        <div id="productDetail">
            <div class="info-msg">正在加载商品详情...</div>
        </div>

        <div id="buySection" style="display: none;">
            <div class="quantity-control">
                <label>购买数量:</label>
                <button onclick="decrementQuantity()">-</button>
                <span id="buyQuantity">1</span>
                <button onclick="incrementQuantity()">+</button>
                <span id="stockInfo" style="margin-left: 15px;">库存: 0</span>
            </div>
            <div class="buy-buttons">
                <button id="addToCartBtn" class="add-to-cart">加入购物车</button>
                <button id="buyNowBtn" class="buy-now">立即购买</button>
            </div>
            <div id="msg" class="mt-20"></div>
        </div>

        <div class="card mt-20 reviews-section">
            <h3>买家评价</h3>
            <div id="sellerReviews">
                <div class="info-msg">正在加载评价...</div>
            </div>
        </div>
    </section>
</div>

<script th:inline="javascript">
    // 从Model中获取商品ID
    const productId = /*[[${productId}]]*/ null;
    console.log("商品详情页面加载，商品ID:", productId);

    // 全局变量
    let product = null;
    let maxQuantity = 0;

    // 加载商品信息
    async function loadProduct() {
        try {
            console.log("正在加载商品ID:", productId);

            const apiUrl = `/api/products/${productId}`;
            console.log("API请求URL:", apiUrl);

            const response = await fetch(apiUrl);
            console.log("API响应状态:", response.status);

            if (!response.ok) {
                document.getElementById('productDetail').innerHTML =
                    `<div class="error-msg">加载商品失败: 服务器错误 (${response.status})</div>`;
                return;
            }

            const data = await response.json();
            console.log("商品数据:", data);
            console.log("商品图片路径:", data.product ? data.product.imageUrl : "无");
            console.log("商品评分数据:", data.buyerResponseScore);

            if (data.error) {
                document.getElementById('productDetail').innerHTML =
                    `<div class="error-msg">${data.error}</div>`;
                return;
            }

            if (!data.product) {
                document.getElementById('productDetail').innerHTML =
                    `<div class="error-msg">商品数据不完整</div>`;
                return;
            }

            product = data.product;
            const sellable = data.sellable === true;
            console.log("商品对象:", product);

            // 构建新的HTML布局
            let html = `<div class="product-detail-container">`;

            // 左侧图片区域
            html += `<div class="product-image-section">`;
            html += `<div class="product-image-container">`;
            if (product.imageUrl) {
                let imageUrl = product.imageUrl;
                if (!imageUrl.startsWith('http') && !imageUrl.startsWith('/')) {
                    imageUrl = '/' + imageUrl;
                }
                console.log("图片URL:", imageUrl);

                // 添加图片，优化图片加载失败处理，但不再显示调试信息
                html += `
                <img src="${imageUrl}" alt="${product.name}" class="product-image"
                     onerror="
                        console.error('图片加载失败:', this.src);
                        // 尝试使用不同的路径格式
                        if(!this.retried) {
                            this.retried = true;
                            console.log('尝试其他路径格式');
                            let newSrc = '${product.imageUrl}';
                            if(newSrc.startsWith('/')) {
                                newSrc = newSrc.substring(1);
                            } else {
                                newSrc = '/' + newSrc;
                            }
                            console.log('新尝试路径:', newSrc);
                            this.src = newSrc;
                        } else {
                            this.onerror = null;
                            this.style.display='none';
                            this.parentNode.innerHTML+='<div class=\\'no-image-placeholder\\'><div class=\\'no-image-icon\\'>📷</div>商品图片暂时无法显示</div>';
                        }">
            `;
            } else {
                html += `<div class="no-image-placeholder"><div class="no-image-icon">📷</div>暂无商品图片</div>`;
            }
            html += `</div>`;
            html += `</div>`;

            // 右侧信息区域
            html += `<div class="product-info-section">`;

            // 商品标题和价格
            html += `<div class="product-header">
            <h3>${product.name || '未命名商品'}</h3>
            <div class="product-price"><span class="price-symbol">¥</span>${product.price || '0'}</div>
        </div>`;

            // 商品信息
            html += `<div class="product-info">`;

            html += `
            <div class="info-row">
                <span class="label">描述:</span>
                <span class="value">${product.description || '无'}</span>
            </div>
            <div class="info-row">
                <span class="label">状态:</span>
                <span class="value">${product.status === 'on_sale' ? '上架中' : '已下架'}</span>
            </div>
            <div class="info-row">
                <span class="label">库存:</span>
                <span class="value">${product.quantity || 0}</span>
            </div>`;

            // 添加商品评分信息
            if (data.buyerResponseScore !== undefined) {
                const score = parseFloat(data.buyerResponseScore).toFixed(1);
                console.log("商品评分:", score);
                html += `
                <div class="info-row">
                    <span class="label">商品评分:</span>
                    <span class="value"><span class="star">${score}★</span></span>
                </div>`;
            }

            // 添加卖家信息
            if (product.user) {
                html += `
                <div class="info-row">
                    <span class="label">卖家:</span>
                    <span class="value">${product.user.username || '未知'}</span>
                </div>`;
            }

            // 描述放在最后
            html += `
            <div class="info-row">
                <span class="label">描述:</span>
                <span class="value">${product.description || '无'}</span>
            </div>`;

            html += `</div>`; // 结束商品信息

            html += `</div>`; // 结束右侧信息区域

            html += `</div>`; // 结束容器

            document.getElementById('productDetail').innerHTML = html;

            // 打印图片URL用于调试
            if (product.imageUrl) {
                console.log("最终图片URL:", product.imageUrl.startsWith('/') ? product.imageUrl : '/' + product.imageUrl);
            }

            // 设置购买区域
            if (sellable && product.quantity > 0) {
                maxQuantity = product.quantity;
                document.getElementById('stockInfo').textContent = `库存: ${product.quantity}`;
                document.getElementById('buySection').style.display = 'block';
            } else {
                document.getElementById('buySection').style.display = 'none';
                document.getElementById('productDetail').innerHTML += `
                <div class="warning-msg">
                    ${product.quantity <= 0 ? '商品库存不足' : '商品当前不可购买'}
                </div>`;
            }

            // 加载评价
            if (product.id) {
                loadProductReviews(product.id);
            } else {
                document.getElementById('sellerReviews').innerHTML = '<p class="no-reviews">无法加载评价：商品信息不完整</p>';
            }

        } catch (error) {
            console.error("加载商品失败:", error);
            document.getElementById('productDetail').innerHTML =
                `<div class="error-msg">加载商品失败: ${error.message || '未知错误'}</div>`;
        }
    }

    // 数量控制函数
    function incrementQuantity() {
        const quantityEl = document.getElementById('buyQuantity');
        let value = parseInt(quantityEl.textContent);
        if (value < maxQuantity) {
            quantityEl.textContent = value + 1;
        } else {
            document.getElementById('msg').innerHTML = '<div class="warning-msg">购买数量不能超过库存</div>';
            setTimeout(() => {
                document.getElementById('msg').innerHTML = '';
            }, 3000);
        }
    }

    function decrementQuantity() {
        const quantityEl = document.getElementById('buyQuantity');
        let value = parseInt(quantityEl.textContent);
        if (value > 1) {
            quantityEl.textContent = value - 1;
        } else {
            document.getElementById('msg').innerHTML = '<div class="warning-msg">购买数量不能少于1</div>';
            setTimeout(() => {
                document.getElementById('msg').innerHTML = '';
            }, 3000);
        }
    }

    // 加载商品评价
    async function loadProductReviews(productId) {
        try {
            console.log("开始加载商品评价，productId:", productId);
            const response = await fetch(`/api/reviews/product/${productId}`);
            if (!response.ok) {
                throw new Error(`HTTP错误 ${response.status}`);
            }
            const reviews = await response.json();
            console.log("已获取评价数据:", reviews);

            // 显示评价
            let reviewsHtml = '';
            if (reviews && reviews.length > 0) {
                reviews.forEach(review => {
                    // 格式化日期
                    const date = review.createdTime ? new Date(review.createdTime).toLocaleDateString('zh-CN') : '未知日期';
                    // 确保评分显示正确
                    const score = review.score ? parseFloat(review.score).toFixed(1) : '0.0';
                    // 获取买家用户名
                    const buyerName = review.buyer ? (review.buyer.username || '匿名用户') : '匿名用户';

                    reviewsHtml += `
                <div class="review-item">
                    <div class="review-header">
                        <div><strong>${buyerName}</strong> <span class="review-score">${score}★</span></div>
                        <div class="review-date">${date}</div>
                    </div>
                    <div class="review-comment">${review.comment || '无评价内容'}</div>
                </div>`;
                });
            } else {
                reviewsHtml = '<p class="no-reviews">暂无相关评价</p>';
            }

            document.getElementById('sellerReviews').innerHTML = reviewsHtml;

        } catch (error) {
            console.error("加载评价失败:", error);
            document.getElementById('sellerReviews').innerHTML = `<div class="error-msg">加载评价失败: ${error.message}</div>`;
        }
    }

    // 加入购物车
    document.getElementById('addToCartBtn').addEventListener('click', async function() {
        const quantity = parseInt(document.getElementById('buyQuantity').textContent);
        try {
            const response = await fetch('/api/carts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify({
                    product: {
                        id: productId
                    },
                    quantity: quantity
                })
            });

            const result = await response.json();

            if (result.error) {
                document.getElementById('msg').innerHTML = `<div class="error-msg">${result.error}</div>`;
            } else {
                document.getElementById('msg').innerHTML = `<div class="success-msg">已成功加入购物车</div>`;
            }

            setTimeout(() => {
                document.getElementById('msg').innerHTML = '';
            }, 3000);

        } catch (error) {
            document.getElementById('msg').innerHTML = `<div class="error-msg">操作失败: ${error.message}</div>`;
        }
    });

    // 立即购买
    document.getElementById('buyNowBtn').addEventListener('click', async function() {
        const quantity = parseInt(document.getElementById('buyQuantity').textContent);

        try {
            document.getElementById('msg').innerHTML = `<div class="info-msg">处理中...</div>`;

            // 先将商品加入购物车
            const response = await fetch('/api/carts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
                body: JSON.stringify({
                    product: {
                        id: productId
                    },
                    quantity: quantity
                })
            });

            const result = await response.json();

            if (result.error) {
                document.getElementById('msg').innerHTML = `<div class="error-msg">${result.error}</div>`;
                return;
            }

            // 跳转到购物车页面
            window.location.href = '/cart';
        } catch (error) {
            document.getElementById('msg').innerHTML = `<div class="error-msg">操作失败: ${error.message}</div>`;
        }
    });

    // 页面加载完毕后执行
    document.addEventListener('DOMContentLoaded', loadProduct);
</script>

</body>
</html> 